package net.pingfang.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

/**
 * XXX
 *
 * @author: CM
 * @date: 2023/3/15
 */
public class AESUtil {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static final String CHARSET = "UTF-8";

    private static Key generateKey(byte[] keyBytes) throws Exception {
        return new SecretKeySpec(keyBytes, ALGORITHM);
    }

    public static String encrypt(String plainText, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, generateKey(key.getBytes(CHARSET)));
        byte[] cipherTextBytes = cipher.doFinal(plainText.getBytes(CHARSET));
        return Base64.getEncoder().encodeToString(cipherTextBytes);
    }

    public static String decrypt(String cipherText, String key) {
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, generateKey(key.getBytes(CHARSET)));
            byte[] plainTextBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
            return new String(plainTextBytes, CHARSET);
        }catch (Exception exception){

        }
        return null;
    }
}
